package org.wso2.ws.dataservice;

import java.io.ByteArrayInputStream;
import java.rmi.RemoteException;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.wso2.ws.dataservice.StudentMySQLReaderProxyStub.Student;
import org.wso2.ws.dataservice.StudentMySQLReaderProxyStub.StudentsE;

public class StudentListClient {
	public Student[] getStudentList() {
		try {
			StudentMySQLReaderProxyStub stub = new StudentMySQLReaderProxyStub(
					"http://localhost:8280/services/StudentMySQLReaderProxy");
			StudentsE studentsE = stub.getAllStudents();
			Student[] students = studentsE.getStudents().getStudent();
			return students;
		} catch (AxisFault e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (DataServiceFaultException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		StudentListClient sc = new StudentListClient();
		Student[] students = sc.getStudentList();
		for (int i = 0; i < students.length; i++) {
			System.out.println(students[i].getFirstName());
		}
	}

	public String getStudentDetails(String studentId) {
		try {
			EndpointReference targetEPR = new EndpointReference(
					"http://localhost:8280/services/StudentRecordProxy");

			Options options = new Options();
			options.setTo(targetEPR);

			ConfigurationContext clientConfigurationContext = ConfigurationContextFactory
					.createConfigurationContextFromFileSystem(null, null);
			ServiceClient sender = new ServiceClient(
					clientConfigurationContext, null);
			sender.setOptions(options);
			options.setTo(targetEPR);

			OMElement echoPayload = getPayload(studentId);
			OMElement result = sender.sendReceive(echoPayload);
			if (result != null) {
				System.out.println(result.toString());
				return result.toString();
			}
		} catch (Exception e) {
			// print stack trace as this is a sample..
			e.printStackTrace();
		}
		return "";
	}

	private static OMElement getPayload(String studentId)
			throws XMLStreamException {
		String payload = "<p:getStudentRecord xmlns:p=\"http://ws.wso2.org/dataservice\"><p:StudentID>"
				+ studentId + "</p:StudentID></p:getStudentRecord>";
		return new StAXOMBuilder(new ByteArrayInputStream(payload.getBytes()))
				.getDocumentElement();
	}
}
